<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\DiyForm;
use App\Models\DiyFormContent;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class DiyFormController extends Controller
{
    public function info(int $id)
    {
        $info = DiyForm::find($id);
        $miniType = $this->getMiniType();

        if (!$info || !$info->status || $miniType != $info->mini_type) return $this->error('信息不存在');

        $info->config = json_decode($info->config, true);

        return $this->_success(compact('info'));
    }

    public function submit(Request $request)
    {
        $memberId = auth('api')->user()->id;
        $miniType = $this->getMiniType();

        $lock = Cache::lock('SUBMIT_DIY_FORM_BY_' . $memberId, 10);

        try {
            $lock->block(5);

            $validatedData = Validator::make(
                $request->all(),
                [
                    'id'      => 'required|integer',
                    'content' => 'required|array',
                ],
                [
                    'id.required'      => 'id不能为空',
                    'id.integer'       => 'id参数错误',
                    'content.required' => '内容不能为空',
                    'content.array'    => '内容参数错误',
                ])->validate();

            $info = DiyForm::find($validatedData['id']);

            if (!$info || !$info->status || $miniType != $info->mini_type) return $this->error('信息不存在');

            foreach ($validatedData['content'] as $item) {
                if ($item['is_required'] && !($item['data'] ?? '')) {
                    return $this->error($item['label'] . '不能为空');
                }
            }

            DiyFormContent::create([
                'diy_form_id'      => $info->id,
                'diy_form_name'    => $info->name,
                'diy_form_content' => $info->content,
                'diy_form_img'     => $info->img,
                'member_id'        => $memberId,
                'mini_type'        => $miniType,
                'content'          => json_encode($validatedData['content'])
            ]);
        } catch (LockTimeoutException $le) {
            return $this->error('提交频繁,请稍后再试');
        } catch (\Throwable $e) {
            if (is_a($e, BusinessException::class)) {
                return $this->error($e->getMessage());
            }

            log_exception('自定义表单提交失败', $e);
            return $this->error('提交失败');
        } finally {
            optional($lock)->release();
        }

        return $this->success('提交成功');
    }

    public function submitList(Request $request)
    {
        $memberId = auth('api')->user()->id;
        $miniType = $this->getMiniType();

        $list = DiyFormContent::select(['id', 'diy_form_id', 'diy_form_name', 'created_at'])->where([
            'member_id' => $memberId,
            'mini_type' => $miniType,
        ])->paginate(10);

        return $this->_success([
            'list' => $list->items(),
        ]);
    }

    public function submitInfo(int $id)
    {
        $memberId = auth('api')->user()->id;
        $miniType = $this->getMiniType();

        $info = DiyFormContent::find($id);

        if (!$info || $info->member_id != $memberId || $info->mini_type != $miniType) return $this->error('信息不存在');

        $info->content = json_decode($info->content, true);

        return $this->_success(compact('info'));
    }
}
